<!-- 合同管理 -->
<template>
    <div >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="合同名称">
                            <a-input v-model="contractName" placeholder="请输入合同名称" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="状态">
                            <a-select v-model="contractStatus" placeholder="请选择">
                                <a-select-option v-for="item in contractStatusList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='16' :sm='24'>
                        <a-form-item label="时间">
                            <a-range-picker @change="onDateChange" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type='primary' @click="getData">查询</a-button>
                            <a-button style="margin-left: 20px" type='' v-if="hasPower('createAwardContract')" @click="setAwardContract">设置推广佣金合同</a-button>
                            <a-button style="margin-left: 20px" type='' v-if="hasPower('createLaborContract')" @click="uploadContract">上传合同</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ total: total ,showSizeChanger: true,pageSize: size,}" size="small">
            <div slot="contractStatus" slot-scope="contractStatus">
                <a-badge :status="contractStatus | contractStatusTypeFilter" :text="contractStatus | contractStatusFilter" />
            </div>
            <div slot="remark" slot-scope="remark">
                <ellipsis :length="6" tooltip>{{ remark == '' || !remark ? '-' : remark }}</ellipsis>
            </div>
            <div slot="operation" slot-scope="text,record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="detail(record)">查看合同</a-button>
                    <a-button type="link" @click="setCustomer(record)">设置所属客户</a-button>
                    <a-button type="link" v-if="record.contractStatus == 1" @click="stop(record,0)">停用</a-button>
                    <a-button type="link" v-else @click="stop(record,1)">启用</a-button>
                </div>
            </div>
        </a-table>

        <!-- 设置推广佣金合同、上传合同 -->
        <a-modal 
            v-model="visible" 
            :title="isUpdateContract ? '上传合同' : '设置推广佣金合同'"
            @ok="handleOk" 
            :forceRender="true"
            @cancel="visible = false">
            <div>
                <a-form-model :model="contract" ref="ruleForm" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
                    <a-form-model-item label="合同名称" prop="contractName">
                        <a-input v-model="contract.contractName" placeholder="请输入合同名称" allowClear/>
                    </a-form-model-item>
                    <a-form-model-item label="备注">
                        <a-textarea v-model="contract.remark" placeholder="请输入备注信息" :maxLength="50" allowClear :auto-size="{ minRows: 4, maxRows: 6 }"/>
                    </a-form-model-item>
                    <a-form-model-item label="合同文件" prop="contractUrl" >
                        <a-upload
                            name="file"
                            @change="handleChange"
                            :before-upload="beforeUpload"
                            :fileList = fileList
                            accept=".pdf,.jpg,.png,.jpeg"
                            :remove="()=>{fileList = []}"
                        >
                            <a-button type="primary"> 上传 </a-button>
                            <p class="ant-upload-text" style="margin-top: 10px">
                                仅支持上传PDF、jpg、png、jpeg格式，文件大小最多20M
                            </p>
                        </a-upload>
                        <div slot="help" class="flex spaceBetween alignCenter" v-if="contract.contractFileName">
                            <span>{{contract.contractFileName}}</span>
                            <a-button type='link' @click="detail(contract)">查看</a-button>
                        </div>
                    </a-form-model-item>
                    <a-form-model-item label="模板ID">
                        <a-input v-model="contract.templateId" placeholder="请输入合同模板ID" allowClear/>
                    </a-form-model-item>
                    <a-form-model-item label="个人领佣金需签约" v-if="!isUpdateContract" prop="awardNeedSign">
                        <a-radio-group v-model="contract.awardNeedSign" v-decorator="['status', {rules: [{required: true,}], initialValue: 1 }]">
                            <a-radio v-for="status in statusList" :key="status.id" :value="status.id">{{status.name}}</a-radio>
                        </a-radio-group>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>

        <!-- 设置所属客户 -->
        <a-modal 
            v-model="clientVisible" 
            title="设置所属客户"
            @ok="clientHandleOk" 
            @cancel="clientVisible = false">
            <div>
                <a-form-model :model="clients" ref="clientsForm" :rules="clientsRules" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
                    <a-form-model-item label="所选客户" prop="customerIds">
                        <a-select mode="multiple" v-model="clients.customerIds" allowClear placeholder="请选择">
                            <a-select-option v-for="client in customerList" :key="client.id" :value="client.id">{{client.customerName}}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { getContractLaborList , createLaborContract , changeLaborContractState , createAwardContract , getAwardContractDetail , chooseLaborContractCustomer , getContractCustomerList } from '@/api/services/contract';
import { fileUpload } from '@/api/system';
import { Ellipsis } from '@/components';
export default {
    components: {
        Ellipsis,
    },
    data () {
        return {
            contractName: '', // 合同名称
            contractStatus: undefined, // 合同状态
            startTime: '', // 开始时间
            endTime: '', // 结束时间
            contractStatusList: [
                { id: 0, name: '已停用'},
                { id: 1, name: '使用中'},
            ],
            isUpdateContract: false,
            isload: false,
            dataList: [],
            page: 1,
            size: 10,
            total: 0,
            columns,
            visible: false,
            contract: {
                contractName: '', // 合同名称
                contractUrl: '', // 合同链接
                remark: '', // 备注
                awardNeedSign: 1,
                templateId: '', // 模板ID
                contractId: '',
            },
            fileList: [],
            statusList: [
                { id: 1, name: '开启'},
                { id: 0, name: '关闭'},
            ],
            clientVisible: false,
            clients: {
                contractId: '',
                customerIds: [],
            }, // 所选客户
            customerList: [], // 所属客户列表
            rules: {
                contractName: [
                    { required: true, message: '请输入合同名称', trigger: 'blur' },
                ],
                contractUrl: [{ required: true, message: '请上传合同文件', trigger: 'blur' }],
                awardNeedSign: [{ required: true, message: '', trigger: 'blur' }],
            },
            clientsRules: {
                customerIds: [{ required: true, message: '请选择所属客户', trigger: 'blur' }],
            },
        };
    },
    created(){
        this.getData();
    },
    methods: {
        // 日期筛选
        onDateChange(date,dateStr){
            console.log(date,dateStr)
            if(date.length > 0){
                this.startTime = `${dateStr[0]}`
                this.endTime = `${dateStr[1]}`
            }else{
                this.startTime = ''
                this.endTime = ''
            }
            this.getData()
        },
        // 获取账户列表数据
        getData(){
            let _this = this
            const params = {
                'contractName': _this.contractName,
                'contractStatus': _this.contractStatus,
                'startTime': _this.startTime,
                'endTime': _this.endTime,
                'pageSize': _this.size,
                'pageIndex': _this.page,
            }
            getContractLaborList(params)
            .then(res=>{
                if(res.success){
                    _this.dataList = res.data;
                    _this.total = res.totalCount;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 合同上传
        uploadContract(){
            this.$refs.ruleForm.resetFields();
            this.isUpdateContract = true;
            this.contract.contractName = '';
            this.contract.contractFileName = '';
            this.contract.remark = '';
            this.contract.templateId = '';
            this.fileList = []
            this.visible = true;
        },
        // 设置推广佣金合同
        setAwardContract(){
            let _this = this
            _this.$refs.ruleForm.resetFields();
            getAwardContractDetail({})
            .then(res=>{
                if(res.success){
                    this.contract = JSON.parse(JSON.stringify(res.data))
                    this.contract.contractId = res.data.id
                    this.isUpdateContract = false;
                    this.visible = true;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
            
        },
        beforeUpload(file) {
            return false;
        },
        handleChange({file,fileList}){
            let _this = this
            const status = file.status;
            if(file.status === 'removed'){
                this.fileList = []
                return
            }
            this.fileList = fileList
            const formData = new FormData();
            formData.append('multipartFile',file)
            fileUpload(formData)
            .then(res=>{
                if(res.success){
                    _this.contract.contractUrl = res.data
                    _this.$refs.ruleForm.clearValidate()
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 设置推广佣金、上传合同
        handleOk(){
            let _this = this
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    var api = _this.isUpdateContract ? createLaborContract(_this.contract) : createAwardContract(_this.contract);
                    api.then(res=>{
                        if(res.success){
                            _this.visible = false;
                            _this.getData();
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: _this.isUpdateContract ? '上传成功' : '设置成功',
                                duration: 8
                            })
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 设置所选客户
        async setCustomer(item){
            this.clients.contractId = item.id
            await this.getCustomer(item.id);
            this.clientVisible = true;
        },
        clientHandleOk(){
            let _this = this
            _this.$refs.clientsForm.validate(valid => {
                if(valid){
                    chooseLaborContractCustomer(_this.clients)
                    .then(res=>{
                        if(res.success){
                            _this.clientVisible = false;
                            _this.getData();
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '设置成功',
                                duration: 8
                            })
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 查看合同
        detail(item){
            window.open(item.contractUrl);
        },
        // 停用合同
        stop(item,state){
            let _this = this
            _this.$confirm({
                title: '温馨提示',
                okText: state == 0 ? '确认停用' : '确认开启',
                content: state == 0 ? '停用后，新发布项目将不可选择该合同，已发布项目不受影响' : '是否启用当前合同？',
                onOk() {
                    const params = {
                        'contractId': item.id,
                        'state': state,
                    }
                    changeLaborContractState(params)
                    .then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: state == 0 ? '停用成功' : '启用成功',
                                description: state == 0 ? '停用成功' : '启用成功',
                                duration: 8
                            })
                            _this.getData();
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                },
                onCancel() {},
            });
        },
        // 获取用户所有客户列表
        getCustomer(contractId){
            let _this = this
            return new Promise((resolve,reject) => {
                getContractCustomerList(contractId)
                .then(res=>{
                    if(res.success){
                        _this.customerList = res.data.allCustomers;
                        _this.clients.customerIds = res.data.selectedCustomers;
                        resolve();
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
    }
}

</script>
<style scoped>

</style>